<template>
  <section>
    <!-- 工具条 +关键字查询+新增-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="关键字查询"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery" icon="el-icon-refresh-left" >查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd" icon="el-icon-circle-plus">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="success" @click="onsale" icon="el-icon-upload2">上架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="danger" @click="offsale" icon="el-icon-download">下架</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="exportData" icon="el-icon-sold-out">导出</el-button>
        </el-form-item>

        <el-form-item>
          <!-- 默认name="file" -->
          <el-upload class="upload-demo"
                     action="http://localhost:8080/product/importExcel"
                     list-type="text">
            <el-button type="warning" icon="el-icon-sell">导入</el-button>
          </el-upload>
        </el-form-item>


      </el-form>
    </el-col>
    <!--

        @row-dblclick="rowDrawerClick" 点击事件  点击弹出字典明细表数据
    -->
    <!--列表数据-->
    <el-table :data="products" highlight-current-row v-loading="listLoading"
              @selection-change="selsChange" :row-key="getKey" ref="multiTable"
              @row-dblclick="rowDrawerClick"
              style="width: 100%;">
      <el-table-column type="selection" width="55" :reserve-selection="true">
      </el-table-column>
      <el-table-column type="index" label="序号" width="60">
      </el-table-column>
      <el-table-column prop="name" label="服务名称" width="150" sortable>
      </el-table-column>
      <el-table-column prop="costprice" label="成本价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="saleprice" label="售价" width="100" sortable>
      </el-table-column>
      <el-table-column prop="resources" label="服务图片" width="300" sortable>
      </el-table-column>
      <el-table-column prop="salecount" label="销售数量" width="100" sortable>
      </el-table-column>
      <el-table-column prop="state" label="状态" width="100" sortable>
        <template scope="scope">
          <span v-if="scope.row.state==1" style="color: blue">上架</span>
          <span v-if="scope.row.state==0" style="color: red">下架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="onsaletime" label="上架时间" width="160" sortable>
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间" width="160" sortable>
      </el-table-column>
      <el-table-column label="操作">
        <template scope="scope">
          <el-button type="warning" size="small" @click="handleEdit(scope.$index, scope.row)"
                     icon="el-icon-edit-outline">编辑
          </el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)"
                     icon="el-icon-delete">删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条+批量删除+分页栏-->
    <!--
    :disabled="this.sels.length===0"
    当sels长度为0的时候，显示当前属性disabled - 禁用。如果不为0就不禁用
   -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0" icon="el-icon-finished">批量删除
      </el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :page-size="pageSize" :total="totals" :current-page="currentPage"
                     style="float:right;">
      </el-pagination>
    </el-col>

    <!--新增+编辑界面-->
    <!--
      title="添加或修改" - 标题
      :visible.sync="saveFormVisible" - 控制当前对话框是否显示 - 默认为false不显示
      :close-on-click-modal="false" - 点击对话框以外的区域不关闭
      -->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false"
               :destroy-on-close="true">
      <el-form :model="saveForm" label-width="150px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="服务名称" prop="name">
          <el-input v-model="saveForm.name" placeholder="请输入服务名称" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价" prop="costprice">
          <el-input v-model="saveForm.costprice" placeholder="请输入成本价：￥" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="售价" prop="saleprice">
          <el-input v-model="saveForm.saleprice" placeholder="请输入售价：￥" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="服务图片" prop="resources">
          <el-input v-model="saveForm.resources" placeholder="请输入服务图片" auto-complete="off"></el-input>
        </el-form-item>
        <el-row>
          <el-col :span="12">
            <el-form-item label="销售数量" prop="salecount">
              <el-input-number v-model="saveForm.salecount" :min="0" :max="10000" placeholder="请输入销售数量" label="描述文字"
                               auto-complete="off"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="状态" prop="state">
              <el-radio-group v-model="saveForm.state">
                <el-radio :label="0" border>下架</el-radio>
                <el-radio :label="1" border>上架</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="上架时间" prop="onsaletime">
              <el-date-picker v-model="saveForm.onsaletime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请输入上架时间"></el-date-picker>
            </el-form-item>

          </el-col>
          <el-col :span="12">
            <el-form-item label="下架时间" prop="offsaletime">
              <el-date-picker v-model="saveForm.offsaletime" type="datetime" value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="请输入下架时间"></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible = false" icon="el-icon-close">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading" icon="el-icon-check">提交</el-button>
      </div>
    </el-dialog>
  </section>
</template>

<script>

export default {
  data() {
    return {
      //1.分页列表展示的相关数据
      products: [],   //列表数据
      listLoading: false,//关闭加载框
      pageSize: 5,        //当前页数
      currentPage: 1,     //当前页
      totals: 0,          //总条数

      //2.关键字查询
      keyword: '',

      //3.新增/修改
      saveFormVisible: false,//新增/编辑界面是否显示
      title: '',             //新增/修改各自变换标题
      saveForm: {           //新增/修改模型数据
        id: null,
        name: '',
        costprice: null,
        saleprice: null,
        resources: '',
        salecount: null,
        state: null,
        offsaletime: null,
        onsaletime: null,
        createtime: null,
      },
      saveLoading: false,     //保存的加载框 - 默认不显示

      //4.批量删除
      sels: [],//列表选中列


      //5.校验表单项里面的数据u
      saveFormRules: {
        name: [
          {required: true, message: '请输入服务名称', trigger: 'blur'},
          {required: true, message: '请输入服务名称', trigger: 'change'}
        ],
        sn: [
          {required: true, message: '请输入服务编号', trigger: 'blur'},
          {required: true, message: '请输入服务编号', trigger: 'change'}
        ],
      },
      //下拉选的类型的模型数据
      dictionarytypes: {},

    }
  },
  methods: {

    //导出服务列表数据
    exportData() {
      //this.$router.push({ path: '/register' });
      location.href = "http://localhost:8080/product/export";
    },

    //1.获取用户列表---分页
    getProducts() {
      let para = {
        pageSize: this.pageSize,        //当前的页数
        currentPage: this.currentPage,  //当前页
        keyword: this.keyword,          //关键字查询
      };
      this.listLoading = true;         //打开加载框
      this.$http.post("/product", para).then(res => {
        this.products = res.data.data; //给模型数据赋值
        this.totals = res.data.totals;    //计算总条数
        this.listLoading = false;       //关闭加载框
      }).catch(res => {
        this.$message.error("系统繁忙，请稍后再试【400,404】")
      })

    },

    //2.点击分页实现
    handleCurrentChange(currentPage) {
      this.currentPage = currentPage;
      this.getProducts();
    },

    //3.高级查询
    keywordQuery() {
      this.currentPage = 1;
      this.getProducts();
    },

    //4.显示新增界面
    handleAdd: function () {
      this.saveFormVisible = true;
      this.title = "新增",
          //重置from表单
          this.saveForm = {
            id: null,
            name: '',
            costprice: null,
            saleprice: null,
            resources: '',
            salecount: null,
            state: 0,
            offsaletime: null,
            onsaletime: null,
            createtime: null,
          }
    },

    //5.显示修改界面
    handleEdit: function (index, row) {
      this.title = "修改";
      //弹出对话框
      this.saveFormVisible = true;
      //回显数据：创建一个新的空对象{}，然后将row中的数据拷贝一份给{}
      this.saveForm = Object.assign({}, row);

    },

    //6..删除功能逻辑
    handleDel: function (index, row) {
      //elementUi提供确认框 - 点确定之后执行then里面的代码，点击取消执行catch中的逻辑
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.delete("/product/" + row.id).then(res => {
          this.listLoading = false; //关闭加载框
          if (res.data.success) {
            this.$message.success("删除成功"); //提示成功消息

            this.$refs.multiTable.clearSelection();//清空批量删除的事件
            //删除成功之后对当前页的处理【特殊情况：删除最后一页的最后一条数据】
            var totalPage = Math.ceil(this.totals / this.pageSize); //总页数 = 最后一页
            //如果当前页是最后一页                  并且是最后一条数据                  并且不是第一页
            if (this.currentPage == totalPage && (this.totals - 1) % this.pageSize == 0 && this.currentPage != 1) {
              this.currentPage--;
            }
            this.getProducts();
          } else {
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
        this.$message.info("已取消操作");
        this.$refs.multiTable.clearSelection();
      });


    },

    //7.批量删除
    selsChange: function (sels) {
      this.sels = sels;
    },

    //7.跨页批量删除
    getKey(row) {
      return row.id;
    },

    //7.批量删除逻辑
    batchRemove: function () {
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确认批量删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true; //显示加载框
        this.$http.patch("/product", ids).then(res => {
          this.listLoading = false; //隐藏加载框
          if (res.data.success) { //操作成功
            this.$message.success("批量删除成功"); //提示成功消息
            //清空批量删除的事件
            this.$refs.multiTable.clearSelection();
            //批量删除后---当前页值为1
            this.currentPage = 1;
            this.getProducts();
          } else { //操作失败
            this.$message.error("系统繁忙，请稍后重试!!![500]"); //后端500错误走这里
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
        this.$message.info("已取消操作");
        this.$refs.multiTable.clearSelection();
      });
    },

    //8.提交新增表单数据   点击保存提交数据到后端
    saveSubmit: function () {
      //表单验证：表单项中任何一个验证不通过，都不能点击提交
      //所有的ref中名称为saveForm的表单
      this.$refs.saveForm.validate((valid) => {
        if (valid) { //表单验证通过 => 每一个表单项都通过了
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            this.saveLoading = true; //显示加载框
            this.$http.put("/product", this.saveForm).then(res => {
              this.saveLoading = false;  //关闭加载框
              this.saveFormVisible = false; //关闭对话框
              if (res.data.success) {
                this.$message.success(this.title + " : 操作成功"); //提示成功消息
                this.$refs.multiTable.clearSelection();//清空多选sels
                this.getProducts();    //重新加载新列表的数据
              } else {
                //this.$message.error("系统繁忙，请稍后重试!!![500]");
                //打印后端的错误信息
                this.$message.error(res.data.message);
              }
            }).catch(res => {
              this.saveLoading = false;  //关闭加载框
              this.saveFormVisible = false; //关闭对话框
              this.$refs.saveForm.clearValidate();//清除提示
              this.$message.error("系统繁忙，请稍后重试!!![400,404]");
              this.$refs.multiTable.clearSelection();//清空多选sels
            })
          });
        }
      });
    },

    //9.上架
    onsale() {
      if (this.sels.length < 1) {
        this.$message.warning("请选择服务之后再上架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要上架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/onsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.$message.success("上架成功");
            this.getProducts();//重新获取列表
            this.$refs.multiTable.clearSelection();//清空多选sels
          } else { //操作失败
            this.$message.error(res.data.message);
            this.$refs.multiTable.clearSelection();//清空多选sels
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(res => {
        this.$message.error("已取消操作");
        this.$refs.multiTable.clearSelection();//清空多选sels
      })
    },

    //10.下架
    offsale() {
      if (!this.sels || this.sels.length < 1) {
        this.$message.warning("请选择服务之后再下架!!!");
        return;
      }
      //获取数组中每一个对象的id 并形成新的数组
      var ids = this.sels.map(item => item.id);
      this.$confirm('确定要下架吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.$http.patch("/product/offsale", ids).then(res => {
          if (res.data.success) { //操作成功
            this.$message.success("下架成功");
            this.getProducts();
            this.$refs.multiTable.clearSelection();//清空多选sels
          } else { //操作失败
            this.$message.error(res.data.message); //后端500错误走这里
            this.$refs.multiTable.clearSelection();//清空多选sels
          }
        }).catch(res => {
          this.$message.error("系统繁忙，请稍后重试!!![400,404]");
        })
      }).catch(() => {
        this.$message.error("已取消操作");
        this.$refs.multiTable.clearSelection();//清空多选sels
      });
    },
    getDictionarytypes() {
      this.$http.get("/product").then(res => {
        if (res) {
          this.dictionarytypes = res.data;
        }
      })
    },


    //计数用的
    handleChange(value) {
      console.log(value);
    }
  },
  mounted() {
    //页面加载就调用这个方法
    this.getProducts();
  }
}

</script>

<style scoped>

</style>